<style lang="scss">
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "@/uni_modules/uview-ui/index.scss";
</style>
<script>
	import Index from '@/common/index-model.js'
	let index = new Index()
	// let disp = require("./utils/broadcast");
	// let msgStorage = require("./components/chat/msgstorage");
	// let msgType = require("./components/chat/msgtype");
	// import {
	// 	onGetSilentConfig
	// } from './components/chat/pushStorage'

	// function ack(receiveMsg) { // 处理未读消息回执
	// 	var bodyId = receiveMsg.id; // 需要发送已读回执的消息id

	// 	var ackMsg = new uni.WebIM.message("read", uni.WebIM.conn.getUniqueId());
	// 	ackMsg.set({
	// 		id: bodyId,
	// 		to: receiveMsg.from,
	// 	});
	// 	uni.WebIM.conn.send(ackMsg.body);
	// }

	// function onMessageError(err) {
	// 	if (err.type === "error") {
	// 		uni.showToast({
	// 			title: err.errorText,
	// 		});
	// 		return false;
	// 	}

	// 	return true;
	// }

	// function getCurrentRoute() {
	// 	let pages = getCurrentPages();
	// 	if (pages.length > 0) {
	// 		let currentPage = pages[pages.length - 1];
	// 		return currentPage.route;
	// 	}
	// 	return "/";
	// }


	// // 不包含陌生人版本(不接收陌生人消息)
	// function calcUnReadSpot(message) {
	//   let myName = uni.getStorageSync("myUsername");
	//   let members = uni.getStorageSync("member") || []; //好友

	//   var listGroups = uni.getStorageSync("listGroup") || []; //群组
	//   let allMembers = members.concat(listGroups);
	//   let count = allMembers.reduce(function(result, curMember, idx) {
	//     let chatMsgs;
	//     if (curMember.groupid) {
	//       chatMsgs =
	//         uni.getStorageSync(curMember.groupid + myName.toLowerCase()) || [];
	//     } else {
	//       chatMsgs =
	//         uni.getStorageSync(
	//           curMember.name && curMember.name.toLowerCase() + myName.toLowerCase()
	//         ) || [];
	//     }
	//     return result + chatMsgs.length;
	//   }, 0);
	//   getApp().globalData.unReadMessageNum = count;
	//   disp.fire("em.unreadspot", message);
	// }

	// 包含陌生人版本
	// function calcUnReadSpot(message) {
	// 	let myName = uni.getStorageSync("myUsername");
	// 	let pushObj = uni.getStorageSync("pushStorageData")
	// 	let pushAry = pushObj[myName] || []
	// 	uni.getStorageInfo({
	// 		success: function(res) {
	// 			let storageKeys = res.keys;
	// 			let newChatMsgKeys = [];
	// 			let historyChatMsgKeys = [];
	// 			storageKeys.forEach((item) => {
	// 				if (item.indexOf(myName) > -1 && item.indexOf("rendered_") == -1) {
	// 					newChatMsgKeys.push(item);
	// 				}
	// 			});
	// 			let count = newChatMsgKeys.reduce(function(result, curMember, idx) {
	// 				let newName = curMember.split(myName)[0]
	// 				let chatMsgs;
	// 				chatMsgs = uni.getStorageSync(curMember) || [];
	// 				if (pushAry.includes(newName)) return result
	// 				return result + chatMsgs.length;
	// 			}, 0);
	// 			getApp().globalData.unReadMessageNum = count;
	// 			disp.fire("em.unreadspot", message);
	// 		},
	// 	});
	// }

	// function saveGroups() {
	// 	var me = this;
	// 	return uni.WebIM.conn.getGroup({
	// 		limit: 50,
	// 		success: function(res) {
	// 			uni.setStorage({
	// 				key: "listGroup",
	// 				data: res.data,
	// 			});
	// 		},
	// 		error: function(err) {
	// 			console.log(err);
	// 		},
	// 	});
	// }

	export default {
		globalData: {
			phoneNumber: '',
			unReadMessageNum: 0,
			userInfo: null,
			saveFriendList: [],
			saveGroupInvitedList: [],
			isIPX: false, //是否为iphone X
			conn: {
				closed: false,
				curOpenOpt: {},
				open(opt) {
					uni.showLoading({
						title: "正在初始化客户端..",
						mask: true,
					});
					this.curOpenOpt = opt;
					uni.WebIM.conn.open(opt);
					this.closed = false;
				},
				reopen() {
					if (this.closed) {
						//this.open(this.curOpenOpt);
						uni.WebIM.conn.open(this.curOpenOpt);
						this.closed = false;
					}
				},
			},
			onLoginSuccess: function(myName) {
				uni.hideLoading();
				uni.redirectTo({
					url: "../chat/chat?myName=" + myName,
				});
			},

			getUserInfo(cb) {
				var me = this;
				if (this.userInfo) {
					typeof cb == "function" && cb(this.userInfo);
				} else {
					// 调用登录接口
					uni.login({
						success() {
							uni.getUserInfo({
								success(res) {
									me.userInfo = res.userInfo;
									typeof cb == "function" && cb(me.userInfo);
								},
							});
						},
					});
				}
			},

			checkIsIPhoneX: function() {
				const me = this;
				uni.getSystemInfo({
					success: function(res) {
						// 根据 model 进行判断
						if (res.model && res.model.search("iPhone X") != -1) {
							me.isIPX = true;
						}
					},
				});
			},
		},

		onLaunch: function() {
			console.log("###################################################",uni.getStorageSync("userid"))
			let sends = {
				"userId" : uni.getStorageSync("userid")?uni.getStorageSync("userid"):'',
				"clientType":1,
				"pages":'index'
			}
			index.getPublicUserMember(sends, '/visitLog/add', 'post', res => {
				if (res.statusCode == 200 && res.data.success) {
					console.log('日活统计',res)
				} else {
					console.log('日活统计失败',res)
				}
			})
			// uni.hideTabBar();
			uni.showShareMenu();

			if (uni.canIUse('getUpdateManager')) {
				const updateManager = uni.getUpdateManager();
				updateManager.onCheckForUpdate(function(res) {
					console.log(res);
					if (res.hasUpdate) {
						updateManager.onUpdateReady(function() {
							uni.showModal({
								title: '更新提示',
								content: '新版本已经准备好，是否重启应用',
								success: (upres) => {
									if (upres.confirm) {
										updateManager.applyUpdate();
									}
								}
							})
						});
						//===
						updateManager.onUpdateFailed(function() {
							uni.showModal({
								// 新的版本下载失败
								title: '已经有新版本了哟~',
								content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
							});
						});
					} else {

					}
				})
				//--
			} else {
				uni.showModal({
					// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
					title: '提示',
					content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
				});
			}
			uni.authorize({
				scope: 'scope.userLocation',
				success: function() {
					console.log('用户同意了授权')
				}
			})
			// 调用 API 从本地缓存中获取数据
			// uni.setInnerAudioOption({
			//   obeyMuteSwitch: false
			// });
			var me = this;
			var logs = uni.getStorageSync("logs") || [];
			logs.unshift(Date.now());
			uni.setStorageSync("logs", logs);

			uni.WebIM.conn.listen({
				onOpened(message) {
					if (
						getCurrentRoute() == "pagesC/login/login" ||
						getCurrentRoute() == "pages/login_token/login_token"
					) {
						me.globalData.onLoginSuccess(
							uni.getStorageSync("myUsername").toLowerCase()
						);
					}
				},

				onReconnect() {
					uni.showToast({
						title: "重连中...",
						duration: 2000,
					});
				},

				onSocketConnected() {
					uni.showToast({
						title: "socket连接成功",
						duration: 2000,
					});
				},

				onClosed() {
					// uni.showToast({
					// 	title: "网络已断开",
					// 	icon: "none",
					// 	duration: 2000,
					// });
					// uni.redirectTo({
					// 	//url: "/pagesC/login/login",
					// });
					//me.globalData.conn.closed = true;
					//uni.WebIM.conn.close();

					var options = {
						user: uni.getStorageSync('hxuser'),
						pwd: uni.getStorageSync('hxpass'),
						appKey: uni.WebIM.config.appkey,
						success: function(res) {
							//disp.fire("em.invite.againLogin",res);
							uni.setStorageSync('hxtoken', res.access_token);
						},
						error: function() {
							me.globalData.conn.closed = true;
							uni.WebIM.conn.close();
						}
					};
					uni.WebIM.conn.open(options);

					// uni.removeStorageSync('pushStorageData');
					// uni.clearStorageSync();
				},

				onInviteMessage(message) {
					me.globalData.saveGroupInvitedList.push(message);
					disp.fire("em.invite.joingroup", message); // uni.showModal({
					// 	title: message.from + " 已邀你入群 " + message.roomid,
					// 	success(){
					// 		disp.fire("em.invite.joingroup", message);
					// 	},
					// 	error(){
					// 		disp.fire("em.invite.joingroup", message);
					// 	}
					// });
				},

				onReadMessage(message) {
					console.log('已读', message)
				},

				//onPresence为旧版 ，建议参考最新增删好友api文档 ：http://docs-im.easemob.com/im/web/basics/buddy
				onPresence(message) {
					switch (message.type) {
						case "unsubscribe":
							break;
							// 好友邀请列表
						case "subscribe":
							for (let i = 0; i < me.globalData.saveFriendList.length; i++) {
								if (me.globalData.saveFriendList[i].from === message.from) {
									me.globalData.saveFriendList[i] = message;
									disp.fire("em.subscribe");
									return;
								}
							}
							msgStorage.saveReceiveMsg(message, "INFORM"); //存添加好友消息，方便展示通知
							me.globalData.saveFriendList.push(message);
							disp.fire("em.subscribe");

							break;

						case "subscribed":
							uni.showToast({
								title: "添加成功",
								duration: 1000,
							});
							disp.fire("em.subscribed");
							break;

						case "unsubscribed":
							disp.fire("em.unsubscribed");
							break;
						case "direct_joined":
							saveGroups();
							uni.showToast({
								title: "已进群",
								duration: 1000,
							});
							break;
						case "memberJoinPublicGroupSuccess":
							saveGroups();
							uni.showToast({
								title: "已进群",
								duration: 1000,
							});
							break;
						case "invite":
							// 防止重复添加
							for (
								let i = 0; i < me.globalData.saveGroupInvitedList.length; i++
							) {
								if (me.globalData.saveGroupInvitedList[i].from === message.from) {
									me.globalData.saveGroupInvitedList[i] = message;
									disp.fire("em.invite.joingroup");
									return;
								}
							}
							me.globalData.saveGroupInvitedList.push(message);
							disp.fire("em.invite.joingroup");
							msgStorage.saveReceiveMsg(message, "INFORM"); //存添加好友消息，方便展示通知
							break;
						case "unavailable":
							disp.fire("em.contacts.remove");
							disp.fire("em.group.leaveGroup", message);
							break;

						case "deleteGroupChat":
							disp.fire("em.invite.deleteGroup", message);
							break;

						case "leaveGroup":
							disp.fire("em.group.leaveGroup", message);
							break;

						case "removedFromGroup":
							disp.fire("em.group.leaveGroup", message);
							break;

						default:
							break;
					}
				},

				onRoster(message) {
					// let pages = getCurrentPages();
					// if(pages[0]){
					// 	pages[0].onShow();
					// }
				},

				onVideoMessage(message) {
					console.log("onVideoMessage: ", message);

					if (message) {
						msgStorage.saveReceiveMsg(message, msgType.VIDEO);
					}

					calcUnReadSpot(message);
					ack(message);
					onGetSilentConfig(message);
				},

				onAudioMessage(message) {
					console.log("onAudioMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.AUDIO);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				onCmdMessage(message) {
					console.log("onCmdMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.CMD);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				// onLocationMessage(message){
				// 	console.log("Location message: ", message);
				// 	if(message){
				// 		msgStorage.saveReceiveMsg(message, msgType.LOCATION);
				// 	}
				// },
				onTextMessage(message) {
					console.log("onTextMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.TEXT);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				onEmojiMessage(message) {
					console.log("onEmojiMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.EMOJI);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				onPictureMessage(message) {
					console.log("onPictureMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.IMAGE);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				onFileMessage(message) {
					console.log("onFileMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.FILE);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},
				onCustomMessage: function(message) {
					console.log("接收到自定义消息", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.FILE);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},
				onReceivedMessage: function(message) {
					console.log("收到消息送达服务器回执", message);
				}, //收到消息送达服务器回执

				// 各种异常
				onError(error) {

					console.log(error,
					'-----------------------'); // 16: server-side close the websocket connection
					// if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
					//   // if(error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED && !logout){
					//   // if(WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax){
					//   // 	return;
					//   // }
					//   uni.showToast({
					//     title: "websocket 断开",
					//     duration: 1000
					//   });
					//   uni.redirectTo({
					//     url: "../login/login"
					//   });
					//   logout = true;
					//   return;
					// } // 8: offline by multi login

					// if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
					//   uni.showToast({
					//     title: "offline by multi login",
					//     duration: 1000
					//   });
					//   uni.redirectTo({
					//     url: "../login/login"
					//   });
					// }
					if (error.type == 28) {
						console.log(uni.getStorageSync('hxname'), '-', uni.getStorageSync('hxPassword_'))
						var options = {
							user: uni.getStorageSync('hxuser'),
							pwd: uni.getStorageSync('hxpass'),
							appKey: uni.WebIM.config.appkey,
							success: function(res) {
								disp.fire("em.invite.againLogin", res);
								uni.setStorageSync('hxtoken', res.access_token);
							},
							error: function() {

							}
						};
						uni.WebIM.conn.open(options);
					}

					if (error.type == uni.WebIM.statusCode.WEBIM_CONNCTION_OPEN_ERROR) {
						uni.hideLoading();
						disp.fire("em.error.passwordErr"); // uni.showModal({
						// 	title: "用户名或密码错误",
						// 	confirmText: "OK",
						// 	showCancel: false
						// });
					}

					if (error.type == uni.WebIM.statusCode.WEBIM_CONNCTION_AUTH_ERROR) {
						uni.hideLoading();
						disp.fire("em.error.tokenErr");
					}

					if (error.type == "socket_error") {
						///sendMsgError
						console.log("socket_errorsocket_error", error);
						uni.showToast({
							title: "网络已断开",
							icon: "none",
							duration: 2000,
						});
						disp.fire("em.error.sendMsgErr", error);
					}
				},
			});

		},
		onShow: function() {

		},
		onHide: function() {
			console.log('App Hide')
			uni.removeStorageSync('EquipmentNo')
			uni.removeStorageSync('EquipmentBlueName')
		}
	}
</script>

<style>
	/* 引入uni官方库 */
	/* @import url("./static/css/uni.css"); */

	* {
		margin: 0px;
		padding: 0px;
	}

	.content {
		width: 100%;
		height: auto;
	}

	block {
		margin: 0px;
		padding: 0px;
	}

	.fonb {
		font-weight: bold;
	}
</style>